package com.example.qianjun.gobang01;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.qianjun.gobang01.bean.Constant;
import com.example.qianjun.gobang01.util.ReferenceInit;
import com.example.qianjun.gobang01.view.GobangPanel;

import java.util.Timer;
import java.util.TimerTask;

public class GobangActivity extends AppCompatActivity implements View.OnClickListener {

    private GobangPanel gobangPanel;
    //倒计时
    private TextView countDown;

    //倒计时数字
    private TextView countDownShow;
    //设置的200ms，计数5次，改变计时
    int showtimeNum = 0;

    //存储前一时刻正在下棋的棋手
    private boolean previousPiece = false;

    //显示信息：当前棋手、获胜棋手
    private TextView currentPlyer;

    //当前玩家棋子
    private ImageView currentplayerImage;
    //分别是悔棋、认输、提示、重玩
    private Button pieceBack;
    private Button giveUp;
    private Button promptPiece;
    private Button startNewGame;

    //倒计时的时间，默认30s
    private int countDownTime = Constant.COUNT_DOWN_NUMBER_30;
    private int countDownTimeMinus = countDownTime;
    //定时器
    private Timer timer;
    private TimerTask timerTask;

    //创建Handler
    private Handler handler;

    //设置存储
    private SharedPreferences sharedPreferences;

    /*初始化参数：
    *对局模式：人人、人机
    *对局顺序：执黑先行，执白先行、执黑后手、执白后手
    * 棋盘大小
    * 机器人等级：傻瓜级、入门级、初学级、高手级、专家级
    * 提示机器人等级：傻瓜级、入门级、初学级、高手级、专家级
    * 落子点边框类型：方形、圆形
    */
    private int chessMode = Constant.HUMAN_PK_HUMAN;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gobang);

        findViewInit();
        listenerinit();
        //参数初始化要放到view初始化后面
        paraInit();


    }

    //视图空间初始化，通过ID查找view
    private void findViewInit() {
        gobangPanel = (GobangPanel) findViewById(R.id.gobangpanel);
        countDown = (TextView) findViewById(R.id.countDown);
        countDownShow = (TextView) findViewById(R.id.countDownShow);
        currentPlyer = (TextView) findViewById(R.id.currentPlayer);
        currentplayerImage = (ImageView) findViewById(R.id.currentPlayerImage);
        pieceBack = (Button) findViewById(R.id.pieceBack);
        giveUp = (Button) findViewById(R.id.giveUp);
        promptPiece = (Button) findViewById(R.id.promptPiece);
        startNewGame = (Button) findViewById(R.id.startNewGame);
    }

    /**
     * 页面参数初始化:
     * 对弈模式：人机、人人
     * 对弈顺序：执黑先行、执白先行、执黑后手、执白后手
     * 机器人等级：傻瓜级、新手级、入门级，困难级、专家级
     * 当前棋手：黑棋、白棋
     * 初始化Handler
     * 初始化定时器
     */
    private void paraInit() {

        sharedPreferences = getSharedPreferences("gobangConfig",MODE_PRIVATE);
        //倒计时参数初始化
        countDownTime = sharedPreferences.getInt("countDownTime",Constant.COUNT_DOWN_NUMBER_30);
        countDownTimeMinus = countDownTime;

        Intent intent = getIntent();
        chessMode = intent.getIntExtra("chessMode", Constant.HUMAN_PK_HUMAN);

        goPanelParaInit();

        //初始化前一个棋子
        previousPiece = gobangPanel.ismIsBlackOrWhite();
        setCurrentPlayerImage();

        //Handler初始化
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                int countdownnumber = msg.what;

                //如果时间剩余不足1s，不允许使用提示功能
                if (countdownnumber <= 1) {
                    gobangPanel.setNoticeRobotNextPieceInTime(false);
                }

                //如果计时完毕，则代表本次放弃落子，切换到另一个棋手落子
                if (countdownnumber <= 0) {
                    countDownTimeMinus = countDownTime;
                    showtimeNum = 0;
                    gobangPanel.changPlayer();
                }

                setCurrentPlayerImage();
                setPieceColor();

                //如果胜负未分，则倒计时进行
                if (!ReferenceInit.getGobangCheckboard().isStop()) {
                    countDownShow.setText(countdownnumber + " s");
                }


                //当时间过了1秒，通知机器人下棋
                if (countdownnumber <= countDownTime - 1) {
                    gobangPanel.noticeRobotPlay();
                }



            }
        };

        //定时器与定时任务初始化
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                showtimeNum++;
                Message message = new Message();
                //如果落完一子，则时间重新计时
                if (previousPiece != gobangPanel.ismIsBlackOrWhite()) {
                    previousPiece = gobangPanel.ismIsBlackOrWhite();
                    countDownTimeMinus = countDownTime;
                    showtimeNum = 0;
                }
                if (showtimeNum >= 5) {
                    showtimeNum = 0;

                    countDownTimeMinus = countDownTimeMinus - 1;

                }
                message.what = countDownTimeMinus;
                handler.sendMessage(message);
            }
        };
        //表示1000ms以后，每隔1000ms执行一次
        timer.schedule(timerTask, 200, 200);

    }


    /**
     * 棋盘参数设置：
     * 对局模式
     * 对弈顺序
     * 机器人等级
     */
    private void goPanelParaInit() {


        gobangPanel.setChessMode(chessMode);
        gobangPanel.setChessOrder();


    }

    //设置当前棋手棋子图片
    private void setCurrentPlayerImage() {
        if (!ReferenceInit.getGobangCheckboard().isStop()) {
            setPieceColor();
        } else if(ReferenceInit.getGobangCheckboard().isStop()){
            //如果是平局，隐藏棋子图片，显示平局
            if (gobangPanel.getWinner() == Constant.NO_WINNER) {
                currentPlyer.setText(R.string.nowinnerplayer);
                currentplayerImage.setVisibility(View.INVISIBLE);
            } else {
                //将文字改变为：获胜玩家
                currentPlyer.setText(R.string.winnerPlayer);
                setPieceColor();
            }

        }

    }

    //设置棋子颜色
    private void setPieceColor() {
        if (gobangPanel.ismIsBlackOrWhite()) {
            currentplayerImage.setImageResource(R.drawable.stone_b1);
        } else {
            currentplayerImage.setImageResource(R.drawable.stone_w2);
        }
    }


    /**
     * 监听事件初始化
     */
    private void listenerinit() {
        pieceBack.setOnClickListener(this);
        giveUp.setOnClickListener(this);
        promptPiece.setOnClickListener(this);
        startNewGame.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.pieceBack:
                gobangPanel.backToPreviousOneOrTwoStep();
                countDownTimeMinus = countDownTime;
                showtimeNum = 0;
                break;
            case R.id.giveUp:
                gobangPanel.giveUp();
                setCurrentPlayerImage();
                break;
            case R.id.promptPiece:
                if (!ReferenceInit.getGobangCheckboard().isStop()) {
                    gobangPanel.setNoticeRobotNextPieceInTime(true);
                    gobangPanel.noticeNextPiece();
                }

                break;
            case R.id.startNewGame:
                restartNewGame();

                break;
        }
    }

    //开始新的对局
    private void restartNewGame() {
        goPanelParaInit();
        gobangPanel.init();
        //玩家信息初始化
        currentPlyer.setText(R.string.currentPlayer);
        currentplayerImage.setVisibility(View.VISIBLE);
        setCurrentPlayerImage();
        //倒计时初始化
        countDownTimeMinus = countDownTime;
        showtimeNum = 0;
        gobangPanel.invalidate();
    }


    /*
    *页面销毁时，取消定时器
    *
    */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
}
